import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.util.concurrent.TimeUnit;

@Slf4j
public class NettyClient {
    private Bootstrap bootstrap;

    public void buildBootStrap() {
        bootstrap = new Bootstrap()
                .group(new NioEventLoopGroup())
                .channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY,true)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) {
                        ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
                            @Override
                            public void channelActive(ChannelHandlerContext ctx) {
                                log.info("######### 连接{}成功 ,{}", ctx.channel().remoteAddress(),this);
                            }

                            @Override
                            public void channelInactive(ChannelHandlerContext ctx) {
                                log.info("######### 连接{}断开 ", ctx.channel().remoteAddress());
                                //连接断开后重连
                                InetSocketAddress socketAddress = (InetSocketAddress) ctx.channel().remoteAddress();
                                ctx.channel().eventLoop().schedule(() -> {
                                    connect(socketAddress.getHostName(), socketAddress.getPort());
                                }, 5, TimeUnit.SECONDS);
                            }

                            @Override
                            public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
                                System.out.println(ctx.channel().remoteAddress().toString() + "$$$" + cause);
                            }
                        });
                        //实际应用添加
                        ch.pipeline().addLast(new LineBasedFrameDecoder(2048));
                        ch.pipeline().addLast(new StringDecoder());
                        ch.pipeline().addLast(new ChannelInboundHandlerAdapter(){
                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                //可以在这里把消息扔出去
                               log.info("收到消息{}",msg);
                            }
                        });
                    }
                });
    }

    /**
     * 支持连接多个服务器 （如果协议相同）
     * @param serverhost
     * @param port
     */
    public void connect(String serverhost, int port) {
        ChannelFuture channelFuture = bootstrap.connect(serverhost, port);
        channelFuture.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture channelFuture)  {
                //如果连接没成功，5秒后自动重连
                if (!channelFuture.isSuccess()) {
                    log.error("######### 连接{}失败，5秒后重连", channelFuture.channel().remoteAddress());
                    channelFuture.channel().eventLoop().schedule(() -> {
                        connect(serverhost, port);
                    }, 5, TimeUnit.SECONDS);
                }
            }
        });
    }
}
